package com.qys.livesMall.navy.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Sets;
import com.qys.livesMall.anchor.constants.RedisConstant;
import com.qys.livesMall.app.user.constants.TencentCloudImConstant;
import com.qys.livesMall.app.user.utils.TencentCloudIm;
import com.qys.livesMall.cache.RedisCache;
import com.qys.livesMall.common.exception.enums.ExceptionEnum;
import com.qys.livesMall.common.message.MessageServer;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.navy.common.Constant;
import com.qys.livesMall.navy.dao.NavyTaskDetailDao;
import com.qys.livesMall.navy.mapper.H2NavyLanguageManageMapper;
import com.qys.livesMall.navy.model.dto.task.AddLivesBulletScreen;
import com.qys.livesMall.navy.model.entity.H2NavyLanguageManage;
import com.qys.livesMall.navy.model.entity.NavyTask;
import com.qys.livesMall.navy.model.entity.NavyTaskDetail;
import com.qys.livesMall.navy.service.NavyLivesBulletScreenService;
import com.qys.livesMall.navy.service.NavyTaskDetailService;
import com.qys.livesMall.navy.service.NavyTaskService;
import com.qys.livesMall.navy.task.TaskInter;
import com.qys.livesMall.shop.open.anchor.service.AnchorServer;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class NavyLivesBulletScreenServiceImpl implements NavyLivesBulletScreenService {
    @Resource
    private MessageServer messageServer;
    @Resource
    private NavyTaskDetailService navyTaskDetailService;
    @Resource
    private H2NavyLanguageManageMapper h2NavyLanguageManageMapper;
    @Resource
    private TencentCloudIm tencentCloudIm;
    @Resource
    private NavyTaskDetailDao navyTaskDetailDao;
    @Resource
    @Lazy
    private TaskInter taskInter;
    @Resource
    private AnchorServer anchorServer;
    @Resource
    private RedisCache redisCache;
    @Resource
    private NavyTaskService navyTaskService;

    @Override
    public R<?> buildTask(AddLivesBulletScreen param) {
        if (param == null || CollectionUtils.isEmpty(param.getNavyIds()) || CollectionUtils.isEmpty(param.getLiveIds())) {
            return messageServer.failMsg(ExceptionEnum.PARAM_IS_ERROR);
        }
        NavyTask navyTask = new NavyTask();
        navyTask.setTaskType(Constant.TaskType.LIVES_BULLET_SCREEN);
        navyTask.setTaskName("直播弹幕");
        navyTask.setTaskParam(JSONObject.toJSONString(param));
        navyTask.setTaskStatus(Constant.TaskStatus.RUNNING);
        navyTask.setTaskStartTime(LocalDateTime.now());
        navyTask.setCreateDate(LocalDateTime.now());
        navyTask.setUpdDate(LocalDateTime.now());
        navyTaskService.save(navyTask);
        //创建任务明细
        NavyTaskDetail detail = new NavyTaskDetail();
        detail.setTaskId(navyTask.getId());
        detail.setTaskType(navyTask.getTaskType());
        detail.setSort(1);
        detail.setNavyIds(String.join(",", param.getNavyIds()));
        detail.setLivesIds(String.join(",", param.getLiveIds()));
        detail.setCreateDate(LocalDateTime.now());
        detail.setTaskStatus(Constant.TaskDetailStatus.NO_START);
        navyTaskDetailDao.save(detail);
        taskInter.addLivesBulletScreenTask(1, detail.getId());
        return R.ok();
    }

    @Override
    @Async
    public void exc(Long taskDetailId) {
        NavyTaskDetail detail = navyTaskDetailService.getById(taskDetailId);
        try {
            String[] livesIds = detail.getLivesIds().split(",");
            String[] navyIdList = detail.getNavyIds().split(",");

            for (String livesId : livesIds) {
                //随机获取弹幕
                LambdaQueryWrapper<H2NavyLanguageManage> query = Wrappers.lambdaQuery(H2NavyLanguageManage.class);
                //水军语言类型（0：水军弹幕 1：水军商品评论 2：水军短视频评论）
                query.eq(H2NavyLanguageManage::getType, 0)
                        .last(" ORDER BY RAND() ")
                        .last(" LIMIT " + navyIdList.length);
                List<H2NavyLanguageManage> h2NavyLanguageManages = h2NavyLanguageManageMapper.selectList(query);
                if(CollectionUtils.isEmpty(h2NavyLanguageManages)){
                    detail.setTaskStatus(Constant.TaskDetailStatus.END_FAIL);
                    detail.setTaskDate(LocalDateTime.now());
                    navyTaskDetailService.upById(detail);
                    navyTaskService.watchTaskEnd(detail.getTaskId());
                    return;
                }

                //获取直播间编号
                String roomNumber = anchorServer.getRoomInfoByLivesSessionId(Long.valueOf(livesId));
                if (StringUtils.isNotEmpty(roomNumber)) {
                    for (String navyId : navyIdList) {
                        //计入观看人数
                        String key = RedisConstant.LIVE_ONLINE_NUMBER_PREFIX + livesId;
                        Long size = redisCache.size(key);
                        Set<String> cacheSet;
                        if(size == 0){
                            cacheSet = Sets.newHashSet("navy" + navyId);
                            //伪装进入直播间
                            tencentCloudIm.sendGroupMsg(navyId, anchorServer.getRoomInfoByLivesSessionId(Long.valueOf(livesId)), TencentCloudImConstant.TIM_CUSTOM_ELEM, "enter");
                        } else {
                            cacheSet = redisCache.getCacheSet(key);
                            if(!redisCache.getCacheSet(key).contains("navy" + navyId)){
                                //伪装进入直播间
                                tencentCloudIm.sendGroupMsg(navyId, anchorServer.getRoomInfoByLivesSessionId(Long.valueOf(livesId)), TencentCloudImConstant.TIM_CUSTOM_ELEM, "enter");
                                cacheSet.add("navy" + navyId);
                            }
                        }
                        redisCache.setCacheSet(key, cacheSet);

                        try {
                            Thread.sleep(RandomUtil.randomLong(5000, 10000));
                        } catch (Exception ignored) {

                        }

                        String content = h2NavyLanguageManages.get(RandomUtil.randomInt(h2NavyLanguageManages.size() - 1)).getContent();
                        tencentCloudIm.sendGroupMsg(navyId, anchorServer.getRoomInfoByLivesSessionId(Long.valueOf(livesId)), TencentCloudImConstant.TIM_TEXT_ELEM, content);
                    }
                }
            }
        } catch (Exception e) {
            detail.setTaskStatus(Constant.TaskDetailStatus.END_FAIL);
            detail.setTaskDate(LocalDateTime.now());
            navyTaskDetailService.upById(detail);
            return;
        }
        detail.setTaskStatus(Constant.TaskDetailStatus.END_SUCCESS);
        navyTaskDetailService.upById(detail);
        //同步主任务状态
        navyTaskService.watchTaskEnd(detail.getTaskId());
    }
}
